package com.swt.testdemo.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请填写说明
 *
 * @author sx
 * @date 2019/12/27 12:11
 */
@Slf4j
public class ShiroAuthenticationFilter extends FormAuthenticationFilter {


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
            Subject subject = this.getSubject(request, response);
            if (!subject.isAuthenticated()) {
                response401(request, response);
                return false;
            }
        } catch (Exception e) {
            response401(request, response);
            return false;
        }
        return true;
    }



    /**
     * 将非法请求返回401
     */
    private void response401(ServletRequest req, ServletResponse servletResponse) {
        try {
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
            httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "用户未登录");
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }




}
